namespace HelpDeskTool.Utils;

public static class Tasks
{
	/// <summary>
	/// Try parallel actions as tasks with logging exceptions and without throws this exceptions
	/// </summary>
	/// <exception cref="OperationCanceledException"/>
	public static Task TryParallelRunAsync(Action<Exception>? callBack, ParallelOptions options, Action action1, Action action2, params Action[] actions)
	{
		return Parallel.ForEachAsync(actions.Concat(new[] { action1, action2 }), options, async (action, token) =>
		{
			await Task.Run(() =>
			{
				try
				{
					action();
				}
				catch (Exception e)
				{
					callBack?.Invoke(e);
				}
			}, token);
		});
	}

	/// <summary>
	/// Try parallel execute tasks with logging exceptions and without throws this exceptions
	/// </summary>
	/// <exception cref="OperationCanceledException"/>
	public static Task TryParallelRunAsync(Action<Exception>? callBack, ParallelOptions options, Func<Task> action1, Func<Task> action2, params Func<Task>[] actions)
	{
		return Parallel.ForEachAsync(actions.Concat(new[] { action1, action2 }), options, async (action, token) =>
		{
			try
			{
				await action();
			}
			catch (OperationCanceledException)
			{
				throw;
			}
			catch (Exception e)
			{
				callBack?.Invoke(e);
			}
		});
	}
}
